package com.wonder.utils;

import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.vtuzx.core.utils.VtuzxUtil;
import com.wonder.app.domain.PurInspectDetail;
import com.wonder.constant.BillType;
import lombok.Getter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.security.MessageDigest;
import java.util.*;

@Component
public class YzjUtil {

    protected static Logger _logger = LoggerFactory.getLogger(YzjUtil.class);
    @Getter
    protected static String AppId;
    @Getter
    protected static String Secret;
    @Getter
    protected static String JssdkAccesstokenUrl;
    @Getter
    protected static String JssdkGenerateUrl;


    /**
     * 给质检部发送通知
     * @param accesstoken
     * @param data
     * @param billType
     */
    public static void sendMsgToQuality(String accesstoken, Map<String, Object> data, String billType) {
        String billNo = VtuzxUtil.getString(data,"billNo");

        Map<String, Object> paramMap = new HashMap<>();//请求参数
        List<Map<String,Object>> paramList = getUseListQuality();
        String url = JssdkGenerateUrl + accesstoken;
        paramMap.put("itemtitle","有新的单据需要检验");//待办内容 （移动端顶部通知栏显示的内容，为空时则不会有顶部通知）
        paramMap.put("title","待办提醒");//待办主标题 ，一般对应轻应用名称
        paramMap.put("content",String.format("您有新的%s需要您检验，单据编号:%s",billType,billNo));//待办项标题内容显示，选填，如不填，则默认取 title 的值
        paramMap.put("headImg","https://www.yunzhijia.com");//待办在客户端显示的 icon url
        paramMap.put("appId",AppId);
        paramMap.put("params",paramList);
        //https://baike.baidu.com/item/%E4%BA%91%E4%B9%8B%E5%AE%B6/408974
        paramMap.put("url","");//点击该待办时跳转的URL，需要全路径
        //生成的待办所关联的三方业务系统的单据ID(待办的批次号)，
        // [ 对应待办处理中的 sourceitemid ]，其值由三方系统自行设定并需保证其唯一性，被标识重复的请求会被忽略。
        paramMap.put("sourceId",billNo);
        paramMap.put("sync",true);
        //发送待办请求
        RestTemplate restTemplate = new RestTemplate();
        String postForEntity = restTemplate.postForObject(url, paramMap, String.class);
        _logger.info("创建待办返回的信息" +postForEntity);
        Map map = jsonToMap(postForEntity);

    }


    @Value("${yzj.appId}")
    public void setAppId(String appId) {
        AppId = appId;
    }

    @Value("${yzj.secret}")
    public void setSecret(String secret) {
        Secret = secret;
    }

    @Value("${yzj.jssdk_accesstoken_url}")
    public void setJssdkAccesstokenUrl(String jssdkAccesstokenUrl) {
        JssdkAccesstokenUrl = jssdkAccesstokenUrl;
    }

    @Value("${yzj.jssdk_generate_url}")
    public void setjssdkGenerateUrl(String jssdkGenerateUrl) {
        JssdkGenerateUrl = jssdkGenerateUrl;
    }


    /**
     * 有新的单据生成通知仓管部
     * @param accesstoken
     * @param data
     * @param billType
     */
    public static void sendMsgToWare(String accesstoken, Map<String, Object> data, String billType) {
        String billNo = VtuzxUtil.getString(data,"billNo");

        Map<String, Object> paramMap = new HashMap<>();//请求参数
        List<Map<String,Object>> paramList = getUseListWare();

        String url = JssdkGenerateUrl + accesstoken;
        paramMap.put("itemtitle","有新的单据需要审批");//待办内容 （移动端顶部通知栏显示的内容，为空时则不会有顶部通知）
        paramMap.put("title","待办提醒");//待办主标题 ，一般对应轻应用名称
        paramMap.put("content",String.format("您有新的%s需要您审批，单据编号:%s",billType,billNo));//待办项标题内容显示，选填，如不填，则默认取 title 的值
        paramMap.put("headImg","https://www.yunzhijia.com");//待办在客户端显示的 icon url
        paramMap.put("appId",AppId);
        paramMap.put("params",paramList);
        //https://baike.baidu.com/item/%E4%BA%91%E4%B9%8B%E5%AE%B6/408974
        paramMap.put("url","");//点击该待办时跳转的URL，需要全路径
        //生成的待办所关联的三方业务系统的单据ID(待办的批次号)，
        // [ 对应待办处理中的 sourceitemid ]，其值由三方系统自行设定并需保证其唯一性，被标识重复的请求会被忽略。
        paramMap.put("sourceId",billNo);
        paramMap.put("sync",true);
        //发送待办请求
        RestTemplate restTemplate = new RestTemplate();
        String postForEntity = restTemplate.postForObject(url, paramMap, String.class);
        _logger.info("创建待办返回的信息" +postForEntity);
        Map map = jsonToMap(postForEntity);

    }

    /**
     * 仓管部openid集合
     * @return
     */
    private static List<Map<String,Object>> getUseListWare() {
        List<Map<String, Object>> paramList = new ArrayList<>();//openid集合
        Map<String, Object> openMap = new HashMap<>();
        openMap.put("openId", "67dba5f0e4b020c4bfbff7d4");
        Map<String, Object> openMap2 = new HashMap<>();
        openMap2.put("openId", "67d3bbdf025f6700010c3275");
        Map<String, Object> openMap3 = new HashMap<>();
        openMap3.put("openId", "67c7ef04e4b0303e3f0dd9d1");
        Map<String, Object> openMap4 = new HashMap<>();//赵长昆
        openMap3.put("openId", "67eb7d43e4b014fc25e646bf");

        Map<String, Object> openMap5 = new HashMap<>();//曲文杰
        openMap3.put("openId", "67eb7f10e4b014fc25e65681");

        Map<String, Object> openMap6 = new HashMap<>();//曲秀华
        openMap3.put("openId", "67eb7eefe4b00290bfb5b068");

        Map<String, Object> openMap7 = new HashMap<>();//孙震
        openMap3.put("openId", "67eb7eb3e4b00290bfb5ae76");

        Map<String, Object> openMap8 = new HashMap<>();//王英爽
        openMap3.put("openId", "67eb7eb3e4b00290bfb5ae77");

        Map<String, Object> openMap9 = new HashMap<>();//赵静
        openMap3.put("openId", "67eb8405e4b014fc25e68728");

        paramList.add(openMap);
        paramList.add(openMap2);
        paramList.add(openMap3);
        paramList.add(openMap4);
        paramList.add(openMap5);
        paramList.add(openMap6);
        paramList.add(openMap7);
        paramList.add(openMap8);
        paramList.add(openMap9);

        return paramList;
    }

    /**
     * 质检部openid集合
     * @return
     */
    private static List<Map<String,Object>> getUseListQuality() {
        List<Map<String, Object>> paramList = new ArrayList<>();//openid集合
        Map<String, Object> openMap = new HashMap<>();
        openMap.put("openId", "67dba5f0e4b020c4bfbff7d4");
        Map<String, Object> openMap2 = new HashMap<>();
        openMap2.put("openId", "67d3bbdf025f6700010c3275");
        Map<String, Object> openMap3 = new HashMap<>();
        openMap3.put("openId", "67c7ef04e4b0303e3f0dd9d1");

        Map<String, Object> openMap4 = new HashMap<>();//田露臻
        openMap3.put("openId", "67eb87b9e4b0c0928ae30690");

        paramList.add(openMap);
        paramList.add(openMap2);
        paramList.add(openMap3);
        paramList.add(openMap4);

        return paramList;
    }


    /**
     * 采购部openid集合
     * @return
     */
    private static List<Map<String,Object>> getUseListPur() {
        List<Map<String, Object>> paramList = new ArrayList<>();//openid集合
        Map<String, Object> openMap = new HashMap<>();
        openMap.put("openId", "67dba5f0e4b020c4bfbff7d4");
        Map<String, Object> openMap2 = new HashMap<>();
        openMap2.put("openId", "67d3bbdf025f6700010c3275");
        Map<String, Object> openMap3 = new HashMap<>();
        openMap3.put("openId", "67c7ef04e4b0303e3f0dd9d1");

        Map<String, Object> openMap4 = new HashMap<>();//姜艳艳
        openMap3.put("openId", "67eb86d5e4b00290bfb5fba1");

        Map<String, Object> openMap5 = new HashMap<>();//苏娟尧
        openMap3.put("openId", "67eb86d5e4b00290bfb5fba4");

        Map<String, Object> openMap6 = new HashMap<>();//孙晓琳
        openMap3.put("openId", "67eb86d5e4b00290bfb5fba2");

        Map<String, Object> openMap7 = new HashMap<>();//张淼涵
        openMap3.put("openId", "67eb86d5e4b00290bfb5fba3");

        paramList.add(openMap);
        paramList.add(openMap2);
        paramList.add(openMap3);
        paramList.add(openMap4);
        paramList.add(openMap5);
        paramList.add(openMap6);
        paramList.add(openMap7);

        return paramList;
    }

    /**
     * 发送一条待办通知(超重的)通知采购部
     * @param accesstoken
     * @param billNo
     * //openid:64f984d4e4b0274aacd3323a
     */
    public static void sendMsgToPurAbnor(String accesstoken, String billNo) {
        Map<String, Object> paramMap = new HashMap<>();//请求参数
        List<Map<String,Object>> paramList = getUseListPur();//openid集合

        String url = JssdkGenerateUrl + accesstoken;
        paramMap.put("itemtitle","地磅超重异常");//待办内容 （移动端顶部通知栏显示的内容，为空时则不会有顶部通知）
        paramMap.put("title","待办提醒");//待办主标题 ，一般对应轻应用名称
        paramMap.put("content",String.format("地磅超重异常，请到金蝶异常处理单进行处理，单号:%s",billNo));//待办项标题内容显示，选填，如不填，则默认取 title 的值
        paramMap.put("headImg","https://www.yunzhijia.com");//待办在客户端显示的 icon url
        paramMap.put("appId",AppId);
        paramMap.put("params",paramList);
        //https://baike.baidu.com/item/%E4%BA%91%E4%B9%8B%E5%AE%B6/408974
        paramMap.put("url","");//点击该待办时跳转的URL，需要全路径
        //生成的待办所关联的三方业务系统的单据ID(待办的批次号)，
        // [ 对应待办处理中的 sourceitemid ]，其值由三方系统自行设定并需保证其唯一性，被标识重复的请求会被忽略。
        paramMap.put("sourceId",billNo);
        paramMap.put("sync",true);
        //发送待办请求
        RestTemplate restTemplate = new RestTemplate();
        String postForEntity = restTemplate.postForObject(url, paramMap, String.class);
        _logger.info("创建待办返回的信息" +postForEntity);
        Map map = jsonToMap(postForEntity);
    }

    /**
     * 发送一条待办通知
     * @param accesstoken
     * @param detail
     * //openid:64f984d4e4b0274aacd3323a
     */
    public static void sendMsgToPur(String accesstoken, PurInspectDetail detail) {
        Map<String, Object> paramMap = new HashMap<>();//请求参数
        List<Map<String,Object>> paramList = getUseListPur();//openid集合
        String url = JssdkGenerateUrl + accesstoken;
        paramMap.put("itemtitle","采购质检不通过");//待办内容 （移动端顶部通知栏显示的内容，为空时则不会有顶部通知）
        paramMap.put("title","待办提醒");//待办主标题 ，一般对应轻应用名称
        paramMap.put("content",String.format("质检不通过,检验单号:%s,物料名称:%s,不合格数量:%s,收料单号:%s,备注信息:%s",
                detail.getBillNo(),detail.getMaterialName(),detail.getUnqualifiedQty(),detail.getReceiveBillNo(),detail.getRemark()));//待办项标题内容显示，选填，如不填，则默认取 title 的值
        paramMap.put("headImg","https://www.yunzhijia.com");//待办在客户端显示的 icon url
        paramMap.put("appId",AppId);
        paramMap.put("params",paramList);
        //https://baike.baidu.com/item/%E4%BA%91%E4%B9%8B%E5%AE%B6/408974
        paramMap.put("url","");//点击该待办时跳转的URL，需要全路径
        //生成的待办所关联的三方业务系统的单据ID(待办的批次号)，
        // [ 对应待办处理中的 sourceitemid ]，其值由三方系统自行设定并需保证其唯一性，被标识重复的请求会被忽略。
        paramMap.put("sourceId",detail.getBillNo() + detail.getId());
        paramMap.put("sync",true);
        //发送待办请求
        RestTemplate restTemplate = new RestTemplate();
        String postForEntity = restTemplate.postForObject(url, paramMap, String.class);
        _logger.info("创建待办返回的信息" +postForEntity);
        Map map = jsonToMap(postForEntity);

    }

    /**
     *@Author: hdx
     *@CreateTime: 21:31 2020/2/14
     *@param:  * @param null
     *@Description:

     */
    public static String getJSSDKAccessToken() {
        String token = null;
        String url = JssdkAccesstokenUrl;
        Map<String, Object> paramMap = new HashMap<>();//请求参数
        Long timestamp = System.currentTimeMillis();
        paramMap.put("appId", AppId);
        paramMap.put("secret", Secret);
        paramMap.put("timestamp", timestamp);
        paramMap.put("scope", "app");
        String json = postRequestForYunZjiJiaService(url,paramMap);
        _logger.info("获取AccessToken" +json);
        Map map = jsonToMap(json);
        if (map != null) {
            Map<String,Object> data = (Map<String, Object>) map.get("data");
            token = (String) data.get("accessToken");
        }
        return token;
    }




    /**
     *@Author: hdx
     *@CreateTime: 21:41 2020/2/14
     *@param:ticket 根据accessToken生成的JssdkGetticket
     *@param:timestamp 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
     *@param:nonceStr 随机字符串
     *@param:url 当前网页的URL
     *@Description: 构建分享链接的签名

     */
    public static String buildJSSDKSignature(String ticket,String timestamp,String nonceStr ,String url) throws Exception {
        String orderedString = "jsapi_ticket=" + ticket
                + "&noncestr=" + nonceStr + "&timestamp=" + timestamp
                + "&url=" + url;
        System.out.println(orderedString);
        return sha1(orderedString);
    }

    /**
     * sha1 加密JSSDK微信配置参数获取签名。
     *
     * @return
     */
    public static String sha1(String orderedString) throws Exception {
        String ciphertext = null;
        MessageDigest md = MessageDigest.getInstance("SHA-1");
        byte[] digest = md.digest(orderedString.getBytes());
        ciphertext = byteToStr(digest);
        return ciphertext.toLowerCase();
    }
    /**
     * 将字节数组转换为十六进制字符串
     *
     * @param byteArray
     * @return
     */
    private static String byteToStr(byte[] byteArray) {
        String strDigest = "";
        for (int i = 0; i < byteArray.length; i++) {
            strDigest += byteToHexStr(byteArray[i]);
        }
        return strDigest;
    }
    /**
     * 将字节转换为十六进制字符串
     *
     * @param mByte
     * @return
     */
    private static String byteToHexStr(byte mByte) {
        char[] Digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
        char[] tempArr = new char[2];
        tempArr[0] = Digit[(mByte >>> 4) & 0X0F];
        tempArr[1] = Digit[mByte & 0X0F];

        String s = new String(tempArr);
        return s;
    }
    /**
     *@Author: hdx
     *@CreateTime: 21:49 2020/2/14
     *@param:  map
     *@Description:  mapToJson

     */
    public static String mapToJson(Map map){
        Gson gson = new Gson();
        String json = gson.toJson(map);
        return json;
    }

    /**
     *@Author: hdx
     *@CreateTime: 21:37 2020/2/14
     *@param:  json
     *@Description: jsonToMap

     */
    private static Map jsonToMap(String json) {
        Gson gons = new Gson();
        Map map = gons.fromJson(json, new TypeToken<Map>(){}.getType());
        return map;
    }

    /**
     *@Author: hdx
     *@CreateTime: 21:36 2020/2/14
     *@param:  * @param null
     *@Description: 调取云之家接口

     */
    private static String postRequestForYunZjiJiaService(String getAccessTokenUrl,Map<String, Object> paramMap) {
        RestTemplate restTemplate = new RestTemplate();
        String postForEntity = restTemplate.postForObject(getAccessTokenUrl, paramMap, String.class);
//        String json = postForEntity.getBody();
        return postForEntity;
    }

}
